const { repos } = require('../git-server')
const { mkdir } = require('fs/promises')
const { join } = require('path')
const hljs = require('highlight.js/lib/common');
const TyGitCrud = require('ty-git-crud')
const { GIT_PATH } = require('../contants')

module.exports = class GitService {
    create(username, name) {
        return new Promise((resolve, reject) => {
            repos.create(`${username}/${name}`, err => {
                if (err) {
                    reject(err)
                } else {
                    resolve()
                }
            })
        })
    }

    async createUserRoot(username) {
        await mkdir(join(repos.dirMap(), username))
    }

    async treeIndex(username, repoName, branchName) {
        const tyGit = new TyGitCrud(join(GIT_PATH, username))
        const list = await tyGit.fileIndexList(repoName, branchName)
        return list
    }

    async tree(username, repoName, branchName, path) {
        const tyGit = new TyGitCrud(join(GIT_PATH, username))
        const list = await tyGit.fileList(repoName, branchName, path)
        return list
    }

    async blobRaw(username, repoName, branchName, path) {
        const tyGit = new TyGitCrud(join(GIT_PATH, username))
        const blob = await tyGit.blobRaw(repoName, branchName, path)
        return blob
    }

    async blobHighLight(username, repoName, branchName, path) {
        const blob = await this.blobRaw(username, repoName, branchName, path)
        if (blob === null) {
            return null
        }
        const res = hljs.highlightAuto(blob).value
        return res
    }
}